package com.atguigu.order.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;

import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.order.bean.Order;
import com.atguigu.order.feign.ProductFeignClient;
import com.atguigu.order.service.OrderService;
import com.atguigu.product.bean.Product;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

//    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Resource
    DiscoveryClient discoveryClient;

    @Resource
    LoadBalancerClient loadBalancerClient;

    @Resource
    RestTemplate restTemplate;

    @Resource
    private ProductFeignClient productFeignClient;


    @SentinelResource(value = "create",blockHandler="createFallback")
    @Override
    public Order create(Long userId,Long productId) {
//        Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);
        Product product = productFeignClient.getProduct(productId);
        BigDecimal multiply = product.getPrice().multiply(new BigDecimal(product.getNum()));
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(multiply);
        order.setUserId(userId);
        order.setNickName(product.getProductName());
        order.setAddress("江西");
        ArrayList<Product> list = new ArrayList<>();
        list.add(product);
        order.setProductList(list);
//        try {
//            SphU.entry("hhh");
//            //要保护的代码
//        } catch (BlockException e) {
//            //处理被流控的逻辑
//        }
        return order;
    }

    public Order createFallback(Long userId, Long productId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知订单"+productId);
        order.setAddress("异常信息："+e.getClass());
        System.out.println("触发流控兜底回调...........");
        return order;
    }

    //使用注解式负载均衡的远程调用
    private Product getProductFromRemoteWithLoadBalancerAnnotation(Long productId){
        //ip和端口换成服务名就行，加了@LoadBalancer注解的RestTemplate调用会自动进行负载均衡
        String url = "http://service-product/getProduct/"+productId;
        Product product = restTemplate.getForObject(url, Product.class);
        log.info("远程返回:{}",product);
        return product;
    }

    //使用负载均衡的远程调用
    private Product getProductFromRemoteWithLoadBalancer(Long productId){
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        //http://localhost:9000/getProduct/1
        String url = "http://"+choose.getHost()+":"+choose.getPort()+ "/getProduct/"+productId;
        log.info("远程请求:{}",url);
        Product product = restTemplate.getForObject(url, Product.class);
        log.info("远程返回:{}",product);
        return product;
    }

    //没有负载均衡的远程调用
    private Product getProductFromRemote(Long productId){
        ServiceInstance instance = discoveryClient.getInstances("service-product").get(0);
        //http://localhost:9000/getProduct/1
        String url = "http://"+instance.getHost()+":"+instance.getPort()+ "/getProduct/"+productId;
        log.info("远程请求:{}",url);
        Product product = restTemplate.getForObject(url, Product.class);
        log.info("远程返回:{}",product);
        return product;
    }
}
